package service

import (
	"context"
	"fmt"
	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/util/gconv"
	"miaoyuadmin/internal/model"
	"strings"
)

type mainService struct {
}

var mainS = mainService{}

func Main() *mainService {

	return &mainS
}

func (s *mainService) InitInfo(ctx context.Context) (initInfo model.MainInitOutput, err error) {
	userId := gconv.Int(Auth().GetIdentity(ctx))
	fmt.Println("userId", userId)
	homeInfo, homeErr := s.GetHomeInfo(ctx)
	if homeErr != nil {
		fmt.Println("init homeInfo config error")
		err = homeErr
		return
	}
	logoInfo, logoErr := s.GetLogoInfo(ctx)
	if logoErr != nil {
		fmt.Println("init logoInfo config error")
		err = logoErr
		return
	}
	menuInfo, menuErr := s.GetMenuInfo(ctx, userId)
	if menuErr != nil {
		fmt.Println("init menuInfo data error")
		err = menuErr
		return
	}

	initInfo.HomeInfo = homeInfo
	initInfo.LogoInfo = logoInfo
	initInfo.MenuInfo = menuInfo

	return
}

func (s *mainService) GetHomeInfo(ctx context.Context) (info model.MainMenuItem, err error) {
	//var ctx = gctx.New()
	model, _ := g.Cfg().Get(ctx, "maininit.homeinfo")
	err = gconv.Scan(model, &info)
	if err != nil {
		return
	}
	return
}

func (s *mainService) GetLogoInfo(ctx context.Context) (info model.MainMenuItem, err error) {

	model, _ := g.Cfg().Get(ctx, "maininit.logoinfo")
	err = gconv.Scan(model, &info)
	if err != nil {
		return
	}
	return
}

func (s *mainService) GetMenuInfo(ctx context.Context, userId int) (info []model.MainMenuItem, err error) {
	menuList, menuErr := Menu().GetAdminMenuList(ctx, userId)
	if menuErr != nil {
		err = menuErr
		fmt.Println("获取菜单信息错误！", err)
		return
	}
	listLen := len(menuList)
	info = make([]model.MainMenuItem, listLen)
	for k, v := range menuList {
		info[k].Title = v.Title
		if strings.EqualFold(v.PathParam, "") {
			info[k].Href = v.Path
		} else {
			info[k].Href = v.Path + "?" + v.PathParam
		}
		info[k].Icon = v.MenuIcon
		info[k].ParentId = v.ParentId
		info[k].Id = v.Id
		info[k].Target = "_self"

	}
	return
}
